using UnityEditor;
using UnityEngine;
using System.IO;
using System.Collections.Generic;
using UnityEditor.Callbacks;

public class BuildAssets
{
    [MenuItem("HybridCLR/Build/1. Compile Hot-Update DLLs")]
    public static void CompileHotUpdateDlls()
    {
        EditorApplication.ExecuteMenuItem("HybridCLR/CompileDll/ActiveBuildTarget");
        AssetDatabase.Refresh();
        Debug.Log("Hot-update DLLs compiled successfully. You can now build the player (File > Build Settings > Build).");
    }

    [MenuItem("HybridCLR/Build/2. Copy Assemblies for Editor")]
    public static void CopyAssembliesForEditor()
    {
        var target = EditorUserBuildSettings.activeBuildTarget;
        string hotUpdateDllSrcDir = $"HybridCLRData/HotUpdateDlls/{target}";
        string aotMetadataSrcDir = $"HybridCLRData/AssembliesPostIl2CppStrip/{target}";

        string streamingAssetsDir = Application.streamingAssetsPath;

        string aotDestDir = Path.Combine(streamingAssetsDir, "AotMetadata");
        string hotUpdateDestDir = Path.Combine(streamingAssetsDir, "HotUpdateDlls");

        // Ensure source directories exist
        if (!Directory.Exists(hotUpdateDllSrcDir) || !Directory.Exists(aotMetadataSrcDir))
        {
            Debug.LogError($"Source HybridCLR directories not found for target {target}. Did you run HybridCLR/Generate/All or build the player?");
            return;
        }

        // Clean and create destination directories
        if (File.Exists(aotDestDir)) { File.Delete(aotDestDir); AssetDatabase.Refresh(); }
        if (Directory.Exists(aotDestDir)) { Directory.Delete(aotDestDir, true); AssetDatabase.Refresh(); }
        if (File.Exists(hotUpdateDestDir)) { File.Delete(hotUpdateDestDir); AssetDatabase.Refresh(); }
        if (Directory.Exists(hotUpdateDestDir)) { Directory.Delete(hotUpdateDestDir, true); AssetDatabase.Refresh(); }
        
        Directory.CreateDirectory(aotDestDir);
        Directory.CreateDirectory(hotUpdateDestDir);

        // Copy HotUpdate.dll
        File.Copy(Path.Combine(hotUpdateDllSrcDir, "HotUpdate.dll"), Path.Combine(hotUpdateDestDir, "HotUpdate.dll.bytes"), true);
        Debug.Log($"Copied HotUpdate.dll to {hotUpdateDestDir}");

        // Copy AOT metadata assemblies
        List<string> aotMetaAssemblyFiles = new List<string>
        {
            "mscorlib.dll", "System.dll", "System.Core.dll",
            "UnityEngine.CoreModule.dll", "UnityEngine.AssetBundleModule.dll",
            "UnityEngine.UI.dll", "Unity.InputSystem.dll"
        };

        foreach (var assemblyName in aotMetaAssemblyFiles)
        {
            string srcPath = Path.Combine(aotMetadataSrcDir, assemblyName);
            if (File.Exists(srcPath))
            {
                File.Copy(srcPath, Path.Combine(aotDestDir, $"{assemblyName}.bytes"), true);
            }
        }
        
        Debug.Log($"Copied AOT metadata assemblies to {aotDestDir}");
        AssetDatabase.Refresh();
        Debug.Log("[CopyAssembliesForEditor] Finished copying HybridCLR assemblies to StreamingAssets.");
    }

    [PostProcessBuild(1)]
    public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
    {
        Debug.Log("[PostProcessBuild] Starting to copy HybridCLR assemblies...");

        string hotUpdateDllSrcDir = $"HybridCLRData/HotUpdateDlls/{target}";
        string aotMetadataSrcDir = $"HybridCLRData/AssembliesPostIl2CppStrip/{target}";
        
        string buildName = Path.GetFileNameWithoutExtension(pathToBuiltProject);
        string buildDir = Path.GetDirectoryName(pathToBuiltProject);
        string streamingAssetsDir = Path.Combine(buildDir, $"{buildName}_Data/StreamingAssets");
        
        string aotDestDir = Path.Combine(streamingAssetsDir, "AotMetadata");
        string hotUpdateDestDir = Path.Combine(streamingAssetsDir, "HotUpdateDlls");

        // Ensure source directories exist
        if (!Directory.Exists(hotUpdateDllSrcDir) || !Directory.Exists(aotMetadataSrcDir))
        {
            Debug.LogError("Source HybridCLR directories not found. Did you compile the hot-update DLLs and build the player?");
            return;
        }

        // Clean and create destination directories
        if (File.Exists(aotDestDir)) File.Delete(aotDestDir);
        if (Directory.Exists(aotDestDir)) Directory.Delete(aotDestDir, true);
        if (File.Exists(hotUpdateDestDir)) File.Delete(hotUpdateDestDir);
        if (Directory.Exists(hotUpdateDestDir)) Directory.Delete(hotUpdateDestDir, true);
        
        Directory.CreateDirectory(aotDestDir);
        Directory.CreateDirectory(hotUpdateDestDir);

        // Copy HotUpdate.dll - a-ha, we don't copy this for builds that download it
        // File.Copy(Path.Combine(hotUpdateDllSrcDir, "HotUpdate.dll"), Path.Combine(hotUpdateDestDir, "HotUpdate.dll.bytes"), true);

        // Copy AOT metadata assemblies
        List<string> aotMetaAssemblyFiles = new List<string>
        {
            "mscorlib.dll", "System.dll", "System.Core.dll",
            "UnityEngine.CoreModule.dll", "UnityEngine.AssetBundleModule.dll",
            "UnityEngine.UI.dll", "Unity.InputSystem.dll"
        };

        foreach (var assemblyName in aotMetaAssemblyFiles)
        {
            string srcPath = Path.Combine(aotMetadataSrcDir, assemblyName);
            if (File.Exists(srcPath))
            {
                File.Copy(srcPath, Path.Combine(aotDestDir, $"{assemblyName}.bytes"), true);
            }
        }

        Debug.Log("[PostProcessBuild] Finished copying HybridCLR assemblies.");
    }
} 